﻿using System.Diagnostics;
using DesktopToy.Core.Common;
using DesktopToy.Core.Weather;
using Newtonsoft.Json;

namespace DesktopToy.Core;

public class WebApi
{
    // todo: 天气API似乎使用彩云科技的好些：https://docs.caiyunapp.com/weather-api/index.html
    
    // 天气API参考：https://lbs.amap.com/api/webservice/guide/api/weatherinfo
    public static LiveWeather GetLiveWeather(string key, int adcode)
    {
        var url = $"https://restapi.amap.com/v3/weather/weatherInfo?key={key}&city={adcode}&extensions=base";
        var json = JsonConvert.DeserializeObject<dynamic>(Utils.HttpGet(url));
        if (json == null) throw new NullReferenceException("获取实时天气失败");
        
        return new LiveWeather
        {
            Province     = (string)json.lives[0].province,
            City         = (string)json.lives[0].city,
            Weather      = (string)json.lives[0].weather,
            Temperature  = (float)json.lives[0].temperature,
            WindDirection= (string)json.lives[0].winddirection,
            WindPower    = (string)json.lives[0].windpower,
            Humidity     = (float)json.lives[0].humidity,
            ReportTime   = (DateTime)json.lives[0].reporttime
        };
    }
    
    public static IEnumerable<ForecastWeather> GetForecastWeather(string key, int adcode)
    {
        var url = $"https://restapi.amap.com/v3/weather/weatherInfo?key={key}&city={adcode}&extensions=all";
        var json = JsonConvert.DeserializeObject<dynamic>(Utils.HttpGet(url));
        if (json == null) throw new NullReferenceException("获取天气预报失败");

        foreach (var forecast in json.forecasts[0].casts)
        {
            yield return new ForecastWeather
            {
                Date = (DateTime)forecast.date,
                Week = (int)forecast.week,
                DayWeather = (string)forecast.dayweather,
                NightWeather = (string)forecast.nightweather,
                DayTemperature = (float)forecast.daytemp,
                NightTemperature = (float)forecast.nighttemp,
                DayWind = (string)forecast.daywind,
                NightWind = (string)forecast.nightwind,
                DayPower = (string)forecast.daypower,
                NightPower = (string)forecast.nightpower
            };
        }
    }
}